﻿using DevExpress.Data.Filtering;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using System.Reflection;
using System.Windows.Forms;

namespace Inaction.UI.Extensions.ControlExtensions
{
    public static class LookUpEditExtender
    {
        public static void Extend(Control c, Form form)
        {
            if (c is LookUpEdit)
            {
                var lue = c as LookUpEdit;
                lue.Properties.SearchMode = SearchMode.OnlyInPopup;
                lue.Properties.AutoSearchColumnIndex = 0;
                lue.Properties.SortColumnIndex = 0;
                lue.Properties.ImmediatePopup = true;
                lue.KeyDown += lue_KeyDown;
            }
        }

        static void lue_KeyDown(object sender, KeyEventArgs e)
        {
            var lue = sender as LookUpEdit;
            if (lue == null || lue.Properties.ReadOnly == true || lue.Properties.Columns.Count < 2) return;
            var columnInodex = lue.Properties.AutoSearchColumnIndex;
            if (e.KeyData == Keys.Left)
            {
                columnInodex--;
            }
            else if (e.KeyData == Keys.Right)
            {
                columnInodex++;
            }
            lue.Properties.AutoSearchColumnIndex = (columnInodex + lue.Properties.Columns.Count) % lue.Properties.Columns.Count;
            lue.Properties.SortColumnIndex = lue.Properties.AutoSearchColumnIndex;
        }
    }
}